package com.dragon.logical.service.job;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.dragon.common.constant.CronJobConstant;
import com.dragon.common.util.CovertUtil;
import com.dragon.logical.service.auth.IToSendService;
import com.dragon.logical.service.reminder.IDoReminderService;
import com.dragon.repository.entity.DoReminder;
import com.dragon.repository.entity.ToSend;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
public class ScheduleReminderJob extends QuartzJobBean {

    @Autowired
    IDoReminderService reminderService;


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("执行cron定时任务{}", LocalDateTime.now());
        String param = String.valueOf(context.getTrigger().getJobDataMap().get(CronJobConstant.REMINDER_JOB_DATA_MAP.variable()));
        sendDoReminder(param);
    }

    private void sendDoReminder(String jsonString){
        Map<String,String> map = JSON.parseObject(jsonString, Map.class);
        List<Integer> idList = CovertUtil.covertIntegerList(map.get("adminIds"));
        if(idList.size()==0) return;
        List<Integer> adminIdsList = idList.stream().distinct().collect(Collectors.toList());
        adminIdsList.forEach(adminId->{
            DoReminder doReminder = new DoReminder();
            doReminder.setAdminId(adminId);
            doReminder.setFromId(0);
            doReminder.setType(8);
            doReminder.setCorrlelationId(Integer.valueOf(map.get("correlationId")));
            doReminder.setCreateTime(DateUtil.date());
            doReminder.setTitle(String.valueOf(map.get("title")));
            //doReminder.setUrlAddress(sendReminder.pushUrl());
            doReminder.setOperationType(11);
            reminderService.addDoReminder(doReminder);
        });
    }
}
